#include "CameraPingPongBuffer.h"
#include <thread>
#include <iostream>
#include <cstring>
#include <chrono>
#include <atomic>
/// 这是一个测试用例 ///

int main() {
    const size_t buffer_size = 1920 * 1080 * 3; // 假设RGB图像
    CameraPingPongBuffer ping_pong_buffer(buffer_size);
    
    // 使用原子变量控制消费者线程的退出
    std::atomic<bool> producer_finished{false};
    
    // 生产者线程
    std::thread producer([&ping_pong_buffer, &producer_finished]() {
        for (int i = 0; i < 100; ++i) {
            uint8_t* write_buf = ping_pong_buffer.getWriteBuffer();
            if (write_buf) {
                // 在数据开头写入帧序号用于验证
                *reinterpret_cast<int*>(write_buf) = i;
                ping_pong_buffer.commitWrite(sizeof(int) + 1000);
                std::cout << "已写入帧 " << i << std::endl;
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(33));
        }
        producer_finished.store(true); // 生产者完成后设置标志
        std::cout << "生产者线程完成" << std::endl;
    });

    // 消费者线程
    std::thread consumer([&ping_pong_buffer, &producer_finished]() {
        int last_frame_id = -1;
        int processed_count = 0;
        
        // 当生产者未完成时，或者还有可读数据时，继续循环
        while (!producer_finished.load() || ping_pong_buffer.hasReadableData()) {
            size_t data_size;
            const uint8_t* read_buf = ping_pong_buffer.getReadBuffer(data_size);
            if (read_buf) {
                int frame_id = *reinterpret_cast<const int*>(read_buf);
                if (frame_id <= last_frame_id) {
                    std::cout << "错误：读取到旧帧或重复帧 " << frame_id 
                              << " (上一帧ID: " << last_frame_id << ")" << std::endl;
                } else {
                    processed_count++;
                }
                last_frame_id = frame_id;
                std::cout << "正在处理帧" << frame_id << "大小为: " << data_size << std::endl;
                ping_pong_buffer.finishRead();
            } else {
                // 没有数据时稍作等待，避免CPU空转
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
        }
        
        std::cout << "消费者线程完成，总共处理了 " << processed_count << " 帧" << std::endl;
    });
    
    producer.join();
    consumer.join();
    
    std::cout << "程序执行完成" << std::endl;
    return 0;
}
